using System;
using UnityEngine;

namespace Framework {
    public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        private static T s_Instance = null;

        public static T Instance
        {
            get
            {
                if (s_Instance == null)
                {
                    s_Instance = GameObject.FindObjectOfType(typeof(T)) as T;
                    if (s_Instance == null)
                    {
                        GameObject go = new GameObject(typeof(T).Name);
                        s_Instance = go.AddComponent<T>();
                        GameObject parent = GameObject.Find("Boot");
                        if (parent == null)
                        {
                            parent = new GameObject("Boot");
                            GameObject.DontDestroyOnLoad(parent);
                        }
                        if (parent != null)
                        {
                            go.transform.parent = parent.transform;
                        }
                    }
                }

                return s_Instance;
            }
        }

        public static bool HaveInstance()
        {
            return s_Instance != null;
        }

        public static void Release()
        {
            if (s_Instance != null)
            {
                (s_Instance as MonoSingleton<T>).Dispose();
                UnityEngine.GameObject.Destroy(s_Instance.gameObject);
                s_Instance = (T)((object)null);
            }
        }

        private void Awake()
        {
            s_Instance = this as T;
            DontDestroyOnLoad(gameObject);
            Init();
        }
    
        public virtual void Init() {}

        public virtual void Dispose() {}

    }
}